package cn.gs.serializable.old;

// @author gs
import cn.gs.util.stream.TokenReader;
import java.io.IOException;
import java.io.Writer;
import java.util.regex.Pattern;

public class SerialNumber implements ISerialEntity {

    String t;

    @Override
    public <T> T deserialize(Class<T> clazz) {
        if (clazz.isAssignableFrom(Double.class) || clazz == double.class) {
            return (T) Double.valueOf(t);
        } else if (clazz.isAssignableFrom(Float.class) || clazz == float.class) {
            return (T) Float.valueOf(t);
        } else if (clazz.isAssignableFrom(Long.class) || clazz == long.class) {
            return (T) Long.valueOf(t);
        } else if (clazz.isAssignableFrom(Integer.class) || clazz == int.class) {
            return (T) Integer.valueOf(t);
        } else if (clazz.isAssignableFrom(Short.class) || clazz == short.class) {
            return (T) Short.valueOf(t);
        } else if (clazz.isAssignableFrom(Byte.class) || clazz == byte.class) {
            return (T) Byte.valueOf(t);
        } else if (clazz.isEnum()) {
            return (T) Enum.valueOf((Class) clazz, t);
        } else if (clazz.isAssignableFrom(String.class)) {
            return (T) t;
        } else {
            return null;
        }
    }

    @Override
    public Object deserialize() {
        if (t.indexOf('.') > 0 || t.toLowerCase().indexOf('e') > 0) {
            return Double.valueOf(t);
        } else {
            return Integer.valueOf(t);
        }
    }

    @Override
    public boolean serialize(Object o) {
        if (o == null) {
            return false;
        }
        if (o instanceof Double || o instanceof Float
                || o instanceof Long || o instanceof Integer
                || o instanceof Short || o instanceof Byte) {
            t = o.toString();
            return true;
        } else {
            return false;
        }

    }

    @Override
    public void write(Writer writer) throws IOException {
        writer.write(t);
    }
    static final Pattern pattern = Pattern.compile("(-)?(\\d*\\.\\d+|\\d+)((e|E)(\\d)+)?");

    @Override
    public boolean read(TokenReader reader) throws IOException {
        t = reader.get().trim();
        if (pattern.matcher(t).matches()) {
            return true;
        } else {
            reader.back();
            return false;
        }
    }

    @Override
    public String toString(String prefix) {
        return prefix + t;
    }

    @Override
    public String toString() {
        return toString("");
    }
}
